package com.lyn.auxiliarytool.views.adapter;

import android.view.View;
import android.view.ViewGroup;
import androidx.viewbinding.ViewBinding;
import java.util.LinkedList;
import java.util.List;

/**
 * 适配器基类
 * @author longyn 2022/11/30
 * @version 1.0.0
 */
public abstract class BaseAdapter<T, V extends ViewBinding> extends android.widget.BaseAdapter {

    private final List<T> data = new LinkedList<>();

    public void setData(List<T> data) {
        this.data.clear();
        if (data == null){
            return;
        }
        this.data.addAll(data);
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        if (this.data.isEmpty()) {
            return 0;
        }
        return this.data.size();
    }

    @Override
    public T getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder<V> viewHolder;
        if (convertView == null) {
            V viewBinding = getViewBinding();
            convertView = viewBinding.getRoot();
            viewHolder = new ViewHolder<>(viewBinding);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder<V>) convertView.getTag();
        }
        onBindView(viewHolder, this.data.get(position));
        return convertView;
    }

    public abstract V getViewBinding();

    public abstract void onBindView(ViewHolder<V> viewHolder, T t);

    public static class ViewHolder<V> {
        public V v;

        public ViewHolder(V v) {
            this.v = v;
        }
    }
}
